package com.sdd.sg.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * ClassName: GatewayDynamicConfiguration
 * Description: 网关配置类包括Sentinel限流配置 --- 动态规则配置
 * date: 2020/7/7
 *
 * @author xugaojun
 */
@Slf4j
@Configuration
@Component
public class GatewayDynamicConfiguration {

    @Value("${sentinel.nacos.address}")
    private String remoteAddress;
    @Value("${sentinel.rule.namespace}")
    private String nacosNameSpace;
    @Value("${sentinel.group.id}")
    private String groupId;
    @Value("${sentinel.data-id}")
    private String dataId;

    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

    public GatewayDynamicConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                       ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    }

    /**
     * 异常处理器
     *
     * @return
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        // Register the block exception handler for Spring Cloud Gateway.
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    /**
     * sentinel网关过滤器-实现对接到spring-cloud-gateway的关键
     *
     * @return
     */
    @Bean
    @Order(-1)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }


    @PostConstruct
    private void init() {
        loadNamespaceRules();
        registerWriteableDatasource();
        initCustomizedApis();
        initBlockHandler();
    }

    /**
     * 首次加载一遍
     */
    private void loadNamespaceRules() {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);
        properties.put(PropertyKeyConst.NAMESPACE, nacosNameSpace);

        ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(properties, groupId, dataId,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                }));
        FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
        log.info("=====================Nacos:Sentinel[sentinel-dynamic-demo] 拉取资源配置成功===============================");
    }


    /**
     * 注册写入配置数据源
     */
    private void registerWriteableDatasource() {
        WritableDataSource writableDataSource = new WorktableNacos<List<FlowRule>>();
        WritableDataSourceRegistry.registerFlowDataSource(writableDataSource);
        log.info("=====================Nacos:Sentinel[sentinel-dynamic-demo] 配置中心写入数据源注册成功===============================");
    }


    /**
     * 配置自定义API组规则
     */
    private void initCustomizedApis() {
        Set<ApiDefinition> definitions = new HashSet<>();
        ApiDefinition api1 = new ApiDefinition("other-group-api")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    add(new ApiPathPredicateItem().setPattern("/other/group/**")
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});

        ApiDefinition api2 = new ApiDefinition("user-api")
                .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                    add(new ApiPathPredicateItem().setPattern("/user/{id}")
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }});

        definitions.add(api1);
        definitions.add(api2);

        GatewayApiDefinitionManager.loadApiDefinitions(definitions);
    }


    /**
     * 定义限流异常处理器
     */
    private void initBlockHandler() {

        BlockRequestHandler blockHandler = (serverWebExchange, throwable) -> {
            log.error(serverWebExchange.getRequest().getURI() + "-> 已被限流处理");

            Map<String, String> res = new HashMap<>(4);
            res.put("errorCode", "500");
            res.put("message", "系统繁忙,请稍后再试");

            return ServerResponse
                    .status(HttpStatus.OK)
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromObject(res));
        };

        GatewayCallbackManager.setBlockHandler(blockHandler);
    }

    /**
     * 配置规则写入
     *
     * @param <T>
     */
    class WorktableNacos<T> implements WritableDataSource<T> {

        // 当sentinel update 时候
        @Override
        public void write(T value) throws Exception {
            String s = JSON.toJSONString(value);
            // 发布配置
            Properties properties = new Properties();
            properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);
            properties.put(PropertyKeyConst.NAMESPACE, nacosNameSpace); // 指定namespace配置
            ConfigService configService = NacosFactory.createConfigService(properties);
            boolean isPublishOk = configService.publishConfig(dataId, groupId, s);
            log.info("isPublishOk========" + isPublishOk);
        }

        @Override
        public void close() throws Exception {
        }
    }

}
